package com.sihan.swvp.common;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

/**
 * COMMON UTIL
 * 
 * @author jch
 * 
 */
public class CommonUtil {

	public static boolean isEmptyString(Object s) {

		return s == null || s.toString().equals("");
	}

	public static boolean isNum(Object str) {
		if (str instanceof Double || str instanceof Float
				|| str instanceof Integer) {
			return true;
		}
		return String.valueOf(str).matches(
				"^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
	}

	public static String connectMsg(Object... strings) {
		StringBuilder sb = new StringBuilder();
		for (Object string : strings) {
			sb.append(string);
		}

		return sb.toString();
	}

	public static void close(Closeable closeable) {

		try {
			closeable.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static void close(Connection conn) {

		try {
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public static void delete(File file){
		try {
			file.delete();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static Method getSetterMethod(Class<?> cls, String field,
			Class<?>... parameterTypes) {

		try {
			return cls.getMethod(
					CommonUtil.connectMsg("set",
							(field.charAt(0) + "").toUpperCase(),
							field.substring(1)), parameterTypes);
		} catch (Exception e) {
			return null;
		}
	}

	public static String o2intString(Object o) {
		try {

			return (int) Double.parseDouble(o.toString()) + "";
		} catch (Exception e) {
			// TODO: handle exception
			return "";
		}
	}

	public static Integer o2int(Object o) {
		try {

			return (int) Integer.parseInt(o.toString());
		} catch (Exception e) {
			// TODO: handle exception
			return null;
		}
	}

	public static Long o2long(Object o) {
		try {

			return (Long) Long.parseLong(o.toString());
		} catch (Exception e) {
			// TODO: handle exception
			return null;
		}
	}

	public static Double o2double(Object o) {
		try {
			return Double.parseDouble(o.toString());
		} catch (Exception e) {
			return null;
		}
	}

	public static String o2string(Object o) {

		return null == o ? "" : o.toString();
	}

	public static Date o2date(Object date) {
		try {
			return o2date(CommonUtil.o2string(date), "yyyy-MM-dd HH:mm:ss");
		} catch (Exception e) {
			// TODO: handle exception
		}

		return null;
	}

	public static Date long2date(long date) {
		try {
			if (date != 0) {
				return new Date(date);
			}
		} catch (Exception e) {
		}

		return null;
	}

	public static Date long2date(String date) {
		try {
			long d = o2long(date);
			if (d != 0l) {
				return new Date(d);
			}
		} catch (Exception e) {
		}

		return null;
	}

	public static Date o2date(Object date, String fs) {
		SimpleDateFormat format = new SimpleDateFormat(fs);
		try {
			return format.parse(CommonUtil.o2string(date));
		} catch (Exception e) {
			return null;
		}
	}

	public static String date2string(Date date) {
		if (null == date)
			return "";
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		return format.format(date);
	}

	public static String date2string(Date date, String fs) {
		if (null == date)
			return "";
		SimpleDateFormat format = new SimpleDateFormat(fs);

		return format.format(date);
	}

	/**
	 * 获取两个时间的中间点时间 st < ent
	 * 
	 * @param st
	 * @param ent
	 * @return
	 */
	public static Date getCenterTime(Date st, Date ent) {
		long diff = ent.getTime() - st.getTime();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(st);
		calendar.add(Calendar.SECOND, (int) (diff / 1000 / 2));

		return calendar.getTime();
	}

	// public static void main(String[] args) throws ParseException {
	// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd H:m:s");
	//
	//
	// Date center =
	// getCenterTime(format.parse("2016-01-01 0:0:0"),format.parse("2016-03-01 0:0:0"));
	// }

	/**
	 * 获取两个时间相差的小时
	 * 
	 * @param st
	 * @param ent
	 * @return
	 */
	public static int getTimeDiffHour(Date st, Date ent) {
		long diff = ent.getTime() - st.getTime();

		return (int) (diff / 3600000);
	}

	/**
	 * 判断两个时间是否在同一年
	 * 
	 * @param st
	 * @param ent
	 * @return
	 */
	public static boolean isSameYear(Date st, Date ent) {
		Calendar c = Calendar.getInstance();
		c.setTime(st);
		int sty = c.get(Calendar.YEAR);
		c.setTime(ent);
		int enty = c.get(Calendar.YEAR);

		return sty == enty;
	}

	/**
	 * 获取日期所在年份第一天
	 * 
	 * @param date
	 * @return
	 */
	public static Date getYearFirst(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);

		return getYearFirst(c.get(Calendar.YEAR));
	}

	/**
	 * 获取日期所在年份最后一天
	 * 
	 * @param date
	 * @return
	 */
	public static Date getYearLast(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);

		return getYearLast(c.get(Calendar.YEAR));
	}

	/**
	 * 获取日期所在年份最后一天
	 * 
	 * @param date
	 * @return
	 */
	public static Date getYearFirst(int year) {
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, year);
		Date currYearFirst = calendar.getTime();

		return currYearFirst;
	}

	/**
	 * 获取日期所在年份第一天
	 * 
	 * @param date
	 * @return
	 */
	public static Date getYearLast(int year) {
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, year);
		calendar.roll(Calendar.DAY_OF_YEAR, -1);
		Date currYearLast = calendar.getTime();

		return currYearLast;
	}

	/**
	 * 判断日期是否是今年的日期
	 * 
	 * @param date
	 * @return
	 */
	public static boolean isCurentYear(Date date) {

		return isSameYear(date, new Date());
	}

	public static String numberFormat(Object number, int precision) {
		if (null == number) {
			return "0";
		}
		if (isNum(number)) {
			double num = o2double(number);
			if (num == 0) {
				return "0";
			}
			String format = "#0";
			if (precision > 0) {
				format += ".";
				for (int i = 0; i < precision; i++) {
					format += "0";
				}
			}
			java.text.DecimalFormat df = new java.text.DecimalFormat(format);

			return df.format(o2double(number));
		}

		return String.valueOf(number);
	}

	public static Date dateAdd(Date date, int caltype, int add) {
		try {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(caltype, add);

			return calendar.getTime();
		} catch (Exception e) {
			return null;
		}
	}

	public static byte[] getFileData(MultipartFile file) {
		byte[] data = null;
		if (null != file && file.getSize() > 0) {
			InputStream is = null;
			try {
				is = file.getInputStream();
				data = new byte[(int) file.getSize()];
				is.read(data);
			} catch (IOException e) {
				// e.printStackTrace();
			} finally {
				CommonUtil.close(is);
			}
		}

		return data;
	}

	public static boolean contains(Object[] list, Object obj) {
		if (obj == null)
			return false;
		for (Object object : list) {
			if (obj.equals(object)) {
				return true;
			}
		}
		return false;
	}

	public boolean contains(Collection<?> list, Object obj) {
		if (obj == null)
			return false;
		for (Object object : list) {
			if (obj.equals(object)) {
				return true;
			}
		}
		return false;
	}

	public static List<?> split(String s, String split, Class<?> cls) {
		List<Object> list = new ArrayList<Object>();
		String[] sps = s.split(split);
		for (String string : sps) {
			try {
				Object to = JSONObject.parseObject(string, cls);
				list.add(to);
			} catch (Exception e) {
			}
		}

		return list;
	}

	public static  Connection getConnection(String driver,String url,String user,String password) throws SQLException, ClassNotFoundException {
		Class.forName(driver);
		Connection con = DriverManager.getConnection(url, user,password);

		return con;
	}

	public static void close(CloseableHttpClient httpclient) {
		// TODO Auto-generated method stub
		try {
			httpclient.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

	
	/**
     * 时间计算
     * @param date 时间，null为当前时间
     * @param field 对哪个属性进行计算；
     * @param amount 要增加的值
     * @return Date  返回日期
     */
    public static Date addTime(Date date, int field, int amount) {
        date = date == null ? new Date() : date;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        if(field == Calendar.YEAR){
            cal.add(Calendar.YEAR, amount);
        }else if(field == Calendar.MONTH){
            cal.add(Calendar.MONTH, amount);
        }else if(field == Calendar.DATE){
            cal.add(Calendar.DATE, amount);
        }else if(field == Calendar.HOUR){
            cal.add(Calendar.HOUR, amount);
        }else if(field == Calendar.MINUTE){
            cal.add(Calendar.MINUTE, amount);
        }
        else if(field == Calendar.SECOND){
            cal.add(Calendar.SECOND, amount);
        }
        else if(field == Calendar.MILLISECOND){
            cal.add(Calendar.MILLISECOND, amount);
        }
        
        return cal.getTime();
    }


/**
     * 根据开始时间和结束时间返回时间段内的时间集合
     * @param beginDate
     * @param endDate
     * @return
     */
    public static List<String> getDatesBetweenTwoDate(Date beginDate, Date endDate) {  
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Date> lDate = new ArrayList<Date>();
        lDate.add(beginDate);//把开始时间加入集合
        Calendar cal = Calendar.getInstance();
        //使用给定的 Date 设置此 Calendar 的时间
        cal.setTime(beginDate);
        boolean bContinue = true;
        while (bContinue) {
            //根据日历的规则，为给定的日历字段添加或减去指定的时间量
            cal.add(Calendar.DAY_OF_MONTH, 1);
            // 测试此日期是否在指定日期之后
            if (endDate.after(cal.getTime())) {
                lDate.add(cal.getTime());
            } else {
                break;
            }
        }
        lDate.add(endDate);//把结束时间加入集合
        List<String> times = new ArrayList<String>();
        for (Date date : lDate) {
            times.add(sdf.format(date));
        }
        return times;
    }

	
}
